//
//  CNMineCollectNewFolderController.m
//  CsdnPlus
//
//  Created by wxlan on 2019/8/8.
//  Copyright © 2019 CSDN. All rights reserved.
//

#import "CNCreatNewFavoritesController.h"
#import <CNBaseTool/CNCategoryHeader.h>
#import <CNBaseViewTool/CNNoDataView.h>
#import <CNBaseViewTool/UIView+CNEmpty.h>
#import <CNBaseViewTool/CNRefreshGifHeader.h>
#import <CNBaseViewTool/CNRefreshAutoNormalFooter.h>
#import <CNBaseViewTool/CNViewConst.h>

@interface CNCreatNewFavoritesController ()
@property (nonatomic, strong) UIButton *releaseBtn;
@property (nonatomic, strong) UIView *floderTitleView;
@property (nonatomic, strong) UIView *floderDescView;

@property (nonatomic,strong) UITextField *titleField;
@property (nonatomic,strong) UITextField *descField;
@property (nonatomic, strong) CNCollectStatusViewModel *viewModel; 
@property (nonatomic, strong) UISwitch *switchFunc;
@property (nonatomic, assign) BOOL isEdit;
@property (nonatomic, assign) BOOL isPrivate;
@end

@implementation CNCreatNewFavoritesController
- (instancetype)initWithIsEdit:(BOOL)isEdit{
    if (self = [super init]) {
        self.isEdit = isEdit;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.theme_backgroundColor = pageBGColorPicker;
    self.edgesForExtendedLayout = UIRectEdgeNone;

    self.title = self.isEdit?@"编辑收藏夹": @"新建收藏夹";
    [Factory addBlackItemToVC:self];
    [self configUI];
}

- (void)configUI {
    [self addReleaseToVC];
    
    [self.view addSubview:self.floderTitleView];
    [self.view addSubview:self.floderDescView];
    [self.floderTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(72);
    }];
    
    [self.floderDescView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.floderTitleView);
        make.top.equalTo(self.floderTitleView.mas_bottom);
        make.height.mas_equalTo(88);
    }];
    [self creatPrivacySwitchView];
    
    self.titleField.text = self.favoritesModel?self.favoritesModel.Folder.Name:self.favoritesCreatModel.Name;
    self.descField.text = self.favoritesModel?self.favoritesModel.Folder.Description:self.favoritesCreatModel.Description;
}

- (void)addReleaseToVC {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.releaseBtn = btn;
    [btn setTitle: self.isEdit?@"编辑":@"完成" forState:(UIControlStateNormal)];
    [btn theme_setTitleColor:linkAddBtnTextColorPicker forState:UIControlStateDisabled];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:16 weight:(UIFontWeightRegular)]];
    btn.userInteractionEnabled = NO;
    @weakify(self); 
    [btn bk_addEventHandler:^(id sender) {
        @strongify(self);
        [self addNewFolder];
    } forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *menuItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
    //使用弹簧控件缩小菜单按钮和边缘距离
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    UIBarButtonItem *spaceItemRight = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    spaceItem.width =  kIOS11_OR_LATER ? 0 : -10;
    if (kIOS11_OR_LATER) {
        btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0,0, -8);
        btn.hitScale = 3;
    } else {
        [btn sizeToFit];
    }
    spaceItemRight.width = 0;
    self.navigationItem.rightBarButtonItems = @[spaceItem,menuItem];
}

- (void)addNewFolder{
    if (self.isEdit) { // 修改收藏夹
        [MBProgressHUD showMessage:@"编辑中,请稍后..."];
        NSString *favoriteId = self.favoritesModel?self.favoritesModel.FolderID:self.favoritesCreatModel.ID;
        NSInteger IsPrivate = self.favoritesModel?self.favoritesModel.Folder.IsPrivate:self.favoritesCreatModel.IsPrivate;
        [self.viewModel editFolderWithFolderId:favoriteId folderName:self.titleField.text desc:self.descField.text isPrivate:IsPrivate completionHandle:^(NSError *error) {
            [MBProgressHUD hideHUD];
            if (!error) {
                if (self.viewModel.code == 200) {
                    if (self.favoritesModel) {
                        self.favoritesModel.Folder.Name = self.titleField.text;
                        self.favoritesModel.Folder.Description = [self.descField.text isNotBlank]?self.descField.text:@"";
                    } else {
                        self.favoritesCreatModel.Name = self.titleField.text;
                        self.favoritesCreatModel.Description = [self.descField.text isNotBlank]?self.descField.text:@"";
                    }
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    [[NSNotificationCenter defaultCenter] postNotificationName:CNMineCollectFolderEditSuccessNotification object:nil];
                }else{
                    [CSDNTool showAlert:self.viewModel.message?:@"编辑失败，请稍后..." inView:self.view];
                    
                }
            }else{
                [MBProgressHUD hideHUD];

                [CSDNTool showAlert:@"编辑失败，请稍后..." inView:self.view];
            }
        }];
    } else {  // 新建收藏夹
        [MBProgressHUD showMessage:@"发布中,请稍后..."];
        @weakify(self);
        [self.viewModel addFolderWithFolderName:self.titleField.text desc:self.descField.text isPrivate:self.isPrivate completionHandle:^(NSError *error) { 
            [MBProgressHUD hideHUD];
            @strongify(self);
            if (!error) {
                if (self.viewModel.code == 200) {
                    if (self.AddFolderBlock) {
                        self.AddFolderBlock(self.viewModel.editFolderModel);
                    };
                    [self.navigationController popViewControllerAnimated:YES];
                } else {
                    [CSDNTool showAlert:self.viewModel.message?:@"创建失败，请稍后..." inView:self.view];
                }
            } else {
                [MBProgressHUD hideHUD];
                [CSDNTool showAlert:@"创建失败，请稍后..." inView:self.view];
            }
        }];
    }
}

#pragma mark -setter and getter
- (CNCollectStatusViewModel *)viewModel{ 
    if (_viewModel == nil) {
        _viewModel = [[CNCollectStatusViewModel alloc] init];
    }
    return _viewModel;
}
- (UIView *)floderTitleView{
    if (_floderTitleView == nil) {
        _floderTitleView = [[UIView alloc] init];
        
        UILabel *textCountLabel = [[UILabel alloc] init];
        [_floderTitleView addSubview:textCountLabel];
        [textCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(0);
            make.top.mas_equalTo(14);
            make.height.mas_equalTo(20);
            make.width.mas_equalTo(20);
        }];
        textCountLabel.textAlignment = NSTextAlignmentRight;
        textCountLabel.font = [UIFont systemFontOfSize:12];
        textCountLabel.textColor = cellDesTitleTextColor;
        textCountLabel.text = @"15";
        
        [_floderTitleView addSubview:self.titleField];
        [self.titleField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.right.equalTo(textCountLabel.mas_left).offset(-5);
            make.top.height.equalTo(textCountLabel);

        }];
        @weakify(self)
        
        [self.titleField bk_addEventHandler:^(id sender) {
            @strongify(self)
            textCountLabel.text = [NSString stringWithFormat:@"%@",@(15-self.titleField.text.length)];
            if ( [self.titleField.text isNotBlank])
            {
                [self.releaseBtn theme_setTitleColor:naviButtonTextColorPicker forState:(UIControlStateNormal)];
                self.releaseBtn.userInteractionEnabled = YES;
                [self.releaseBtn setTitle:@"完成" forState:UIControlStateNormal];
            }
            else
            {
                [self.releaseBtn theme_setTitleColor:linkAddBtnTextColorPicker forState:(UIControlStateNormal)];
                self.releaseBtn.userInteractionEnabled = NO;
            }
        } forControlEvents:(UIControlEventEditingChanged)];
        
//        [self.titleField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
//            @strongify(self)
//            textCountLabel.text = [NSString stringWithFormat:@"%@",@(15-self.titleField.text.length)];
//            if ( [self.titleField.text isNotBlank])
//            {
//                [self.releaseBtn theme_setTitleColor:naviButtonTextColorPicker forState:(UIControlStateNormal)];
//                self.releaseBtn.userInteractionEnabled = YES;
//                [self.releaseBtn setTitle:@"完成" forState:UIControlStateNormal];
//            }
//            else
//            {
//                [self.releaseBtn theme_setTitleColor:linkAddBtnTextColorPicker forState:(UIControlStateNormal)];
//                self.releaseBtn.userInteractionEnabled = NO;
//            }
//        }];
        UIView *line = [[UIView alloc] init];
        [_floderTitleView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(0);
            make.height.mas_equalTo(0.5);
        }];
        line.theme_backgroundColor = myHeadLineBGColor;
    }
    
    return _floderTitleView;
}

- (UIView *)floderDescView{
    if (_floderDescView == nil) {
        _floderDescView = [[UIView alloc] init];
        
        UITextField *textField = [[UITextField alloc] init];
        [_floderDescView addSubview:textField];
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.top.mas_equalTo(13);
            make.height.mas_equalTo(22);
        }];
        textField.placeholder = @"描述（可选）";
        textField.font = [UIFont systemFontOfSize:16];
        textField.tintColor = naviBGColor;
        textField.theme_placeholderAttributes = [ThemeStringAttributesPicker pickerWithAttributes:@[@{NSForegroundColorAttributeName: cellDesTitleTextColor,NSFontAttributeName:[UIFont systemFontOfSize:16]},@{NSForegroundColorAttributeName: mainTitleNightColor,NSFontAttributeName:[UIFont systemFontOfSize:16]}]];
         [textField setValue:[NSNumber numberWithInt:0] forKey:@"paddingLeft"];
        textField.theme_textColor = cellTitleTextColorPicker;

        self.descField = textField;
        @weakify(self)
        [self.descField bk_addEventHandler:^(id sender) {
            @strongify(self)
            if ( [self.titleField.text isNotBlank])
            {
                [self.releaseBtn theme_setTitleColor:naviButtonTextColorPicker forState:(UIControlStateNormal)];
                self.releaseBtn.userInteractionEnabled = YES;
                [self.releaseBtn setTitle:@"完成" forState:UIControlStateNormal];
            }
            else
            {
                [self.releaseBtn theme_setTitleColor:linkAddBtnTextColorPicker forState:(UIControlStateNormal)];
                self.releaseBtn.userInteractionEnabled = NO;
            }
        } forControlEvents:(UIControlEventEditingChanged)];
//        [self.descField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
//            @strongify(self)
//            if ( [self.titleField.text isNotBlank])
//            {
//                [self.releaseBtn theme_setTitleColor:naviButtonTextColorPicker forState:(UIControlStateNormal)];
//                self.releaseBtn.userInteractionEnabled = YES;
//                [self.releaseBtn setTitle:@"完成" forState:UIControlStateNormal];
//            }
//            else
//            {
//                [self.releaseBtn theme_setTitleColor:linkAddBtnTextColorPicker forState:(UIControlStateNormal)];
//                self.releaseBtn.userInteractionEnabled = NO;
//            }
//        }];
        
    }
    return _floderDescView;
}

-(UITextField *)titleField
{
    if (!_titleField) {
      
        _titleField = [[UITextField alloc]init];
        _titleField.theme_backgroundColor = pageBGColorPicker;
        _titleField.font = [UIFont systemFontOfSize:16];
        _titleField.theme_textColor = cellTitleTextColorPicker;
        _titleField.returnKeyType = UIReturnKeyDefault;
        _titleField.keyboardAppearance = [CNThemesManager isNight] ? UIKeyboardAppearanceDark : UIKeyboardAppearanceDefault;
        _titleField.placeholder = @"标题";
         _titleField.theme_placeholderAttributes = [ThemeStringAttributesPicker pickerWithAttributes:@[@{NSForegroundColorAttributeName: cellDesTitleTextColor,NSFontAttributeName:[UIFont systemFontOfSize:16]},@{NSForegroundColorAttributeName: mainTitleNightColor,NSFontAttributeName:[UIFont systemFontOfSize:16]}]];
        [_titleField setValue:[NSNumber numberWithInt:0] forKey:@"paddingLeft"];
        [_titleField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
 
        _titleField.tintColor = naviBGColor;
    }
    return _titleField;
}

- (void)creatPrivacySwitchView {
    UIView *bgView = [[UIView alloc] init];
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.floderDescView.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(49.0f, 31.0f));
        make.left.right.mas_equalTo(self.floderDescView);
    }];
    
    UILabel *switchDescLabel = [[UILabel alloc] init];
    switchDescLabel.text = @"私密";
    switchDescLabel.theme_textColor = [ThemeColorPicker pickerWithColors:@[@"#CCCCD8", @"#555666"]];
    switchDescLabel.font = [UIFont systemFontOfSize:16];
    [bgView addSubview:switchDescLabel];
    [switchDescLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.left.mas_equalTo(bgView);
    }];
    
    UILabel *switchLabel = [[UILabel alloc] init];
    switchLabel.theme_textColor = [ThemeColorPicker pickerWithColors:@[@"#999AAA", @"#6F6F82"]];
    switchLabel.font = [UIFont systemFontOfSize:14];
    [bgView addSubview:switchLabel];
    [switchLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(bgView);
        make.centerY.mas_equalTo(-2);
    }];
    _switchFunc = [[UISwitch alloc]init];
    
    if (self.isEdit) {
        NSInteger isOn = self.favoritesModel?self.favoritesModel.Folder.IsPrivate:self.favoritesCreatModel.IsPrivate;
        switchLabel.text = isOn?@"私密":@"公开";
        _switchFunc.on = isOn;
    } else {
        switchLabel.text = @"公开";
        _switchFunc.on = self.isPrivate;
    }
    UIView *switchBackView = [[UIView alloc] init];
    if ([CNThemesManager isNight]) {
        switchBackView.backgroundColor = [UIColor clearColor];
    } else {
        switchBackView.backgroundColor = [UIColor colorWithHexString:@"#D9DADD"];
    }
    switchBackView.layer.cornerRadius = 11;
    switchBackView.layer.masksToBounds = YES;
    
    [bgView addSubview:switchBackView];
    [switchBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(bgView).offset(-4);
        make.right.mas_equalTo(switchLabel.mas_left).offset(-8);
        make.size.mas_equalTo(CGSizeMake(35, 22));
    }];
    [_switchFunc setOnTintColor:switchColor];
    [_switchFunc setThumbTintColor:slideBarTextColor];
    _switchFunc.transform = CGAffineTransformMakeScale(0.7, 0.7);
    [switchBackView addSubview:_switchFunc];
    [_switchFunc mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(-3);
        make.left.mas_equalTo(-5);
        make.size.mas_equalTo(CGSizeMake(36, 22));
    }];
    [self.switchFunc bk_addEventHandler:^(UISwitch *sender) {
        if (self.isEdit) {
            if (self.favoritesModel) {
                self.favoritesModel.Folder.IsPrivate = self.switchFunc.on;
            } else {
                self.favoritesCreatModel.IsPrivate = self.switchFunc.on;
            }
            NSInteger isOn = self.favoritesModel?self.favoritesModel.Folder.IsPrivate:self.favoritesCreatModel.IsPrivate;
            switchLabel.text = isOn?@"私密":@"公开";
        } else {
            switchLabel.text = self.switchFunc.on?@"私密":@"公开";
            self.isPrivate = self.switchFunc.on;
        }
        if ([self.titleField.text isNotBlank]) {
            self.releaseBtn.userInteractionEnabled = YES;
            [self.releaseBtn setTitle:@"完成" forState:UIControlStateNormal];
            [self.releaseBtn theme_setTitleColor:naviButtonTextColorPicker forState:(UIControlStateNormal)];
        }
    } forControlEvents:UIControlEventValueChanged];
}

-(void)textFieldDidChange:(UITextField *)textField
{
    
    CGFloat maxLength = 15;
    
   
    NSString *toBeString = textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    if (!position || !selectedRange)
    {
        if (toBeString.length > maxLength)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:maxLength];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}
@end
